<?php
/**
 * Created by PhpStorm.
 * User: Thans
 * Date: 2018/7/15
 * Time: 上午12:20
 */

namespace app\common\service;


use app\common\model\AddonsModel;
use app\common\model\RouteModel;
use think\facade\Route;

class RouteService
{
    protected $route;

    public function __construct()
    {
        $this->route = new RouteModel();
    }

    public function delete($action, $var)
    {
        $full_url = $this->buildFullUrl($action, $var);
        return $this->route->where('full_url', $full_url)->delete();
    }

    public function setRoute($action, $var, $url, $status = 1, $list_order = 1000)
    {
        $full_url = $this->buildFullUrl($action, $var);
        $map['url'] = $url;
        $map['full_url'] = ['<>', $full_url];
        $res = $this->route->where($map)->find();
        if ($res) {
            return ['code' => 4001, 'msg' => '别名url已存在', 'data' => []];
        }
        unset($map['url']);
        $map['full_url'] = $full_url;
        $route = $this->route->where($map)->find();
        if ($route) {
            $route->url = $url;
            $status ? $route->status = $status : '';
            $list_order ? $route->list_order = $list_order : '';
            $res = $route->isUpdate(true)->save();
            if ($res) {
                return ['code' => 1001, 'msg' => '更新成功', 'data' => ''];
            } else {
                return ['code' => 4001, 'msg' => '更新失败', 'data' => []];
            }
        } else {
            $res = $this->route::create([
                'status' => $status,
                'list_order' => $list_order,
                'full_url' => $full_url,
                'url' => $url,
            ]);
            if ($res) {
                return ['code' => 1001, 'msg' => '新增成功', 'data' => ''];
            } else {
                return ['code' => 4002, 'msg' => '新增失败', 'data' => []];
            }
        }
    }

    public function buildFullUrl($action, $vars)
    {
        // 解析参数
        if (is_string($vars)) {
            // aaa=1&bbb=2 转换成数组
            parse_str($vars, $vars);
        }

        if (!empty($vars)) {
            ksort($vars);

            $fullUrl = $action . '?' . http_build_query($vars);
        } else {
            $fullUrl = $action;
        }

        return $fullUrl;
    }

    public function getUrl($action, $vars)
    {
        $full_url = $this->buildFullUrl($action, $vars);

        $url = $this->route->where('full_url', $full_url)->value('url');

        return empty($url) ? '' : $url;
    }

    public function getRoutes()
    {
        $route = cache('alias_roue');
        if ($route) {
            return $route;
        }
        $map['status'] = 1;
        $route = $this->route->where($map)->order('list_order desc')->select();
        cache('alias_route', $route);
        return $route;
    }

    public function loadRoutes()
    {
        $route = $this->getRoutes();
        foreach ($route as $val) {
            Route::get($val['url'], $val['full_url']);
        }
    }

    public function loadAddonsRoutes()
    {
        $routes = cache('init_addons_route');
        if (!$routes) {
            $res = AddonsModel::where('status', 1)->field('d_id')->select();
            foreach ($res as $val) {
                $routes[$val['d_id']] = ADDONS_PATH . $val['d_id'] . '/route.php';
            }
            cache('init_addons_route', $routes, null, 'init_addons_route');
        }
        if (!empty($routes)) {
            foreach ($routes as $key => $val) {
                $route = include $val;
                foreach ($route as $k => $v) {
                    $v[0] = 'addons\\' . $key . '\controller\\' . $v[0];
                    $has = strpos($k, '/');
                    while ($has === 0) {
                        $k = substr($k, 1, strlen($k)-1);
                        $has = strpos($k, '/');
                        if($has != 0){
                            continue;
                        }
                    }
                    $res = Route::getRule($k);
                    if(!$res){
                        Route::rule($k, $v[0], $v[1] ?: '');
                    }
                }
            }
        }
    }
}